package initialize

import (
	"fmt"
	"go.uber.org/zap"
	"goods_srv/global"
	"goods_srv/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

var err error

// 初始化mysql
func InitMysql() {
	//日志打印
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,  // Slow SQL threshold
			LogLevel:                  logger.Error, //只有错误的时候会打印出sql语句，logger.info则会打印出所有的sql语句
			IgnoreRecordNotFoundError: true,         // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,         // Don't include params in the SQL log
			Colorful:                  true,         // 开启彩色打印
		},
	)

	user := global.AppConf.MysqlConfig.User
	password := global.AppConf.MysqlConfig.Password
	host := global.AppConf.MysqlConfig.Host
	port := global.AppConf.MysqlConfig.Port
	dbName := global.AppConf.MysqlConfig.DbName
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		zap.S().Panic("mysql连接失败")
	}
	zap.S().Info("mysql连接成功")
	//数据迁移
	global.DB.AutoMigrate(new(model.Category), new(model.Brands), new(model.GoodsCategoryBrand), new(model.Banner))
}
